package com.syyo.admin.common.security.config;

import com.syyo.admin.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author /
 * token过滤器
 */
@Slf4j
public class TokenFilter extends GenericFilterBean {

   private final TokenProvider tokenProvider;

   TokenFilter(TokenProvider tokenProvider) {
      this.tokenProvider = tokenProvider;
   }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {
      HttpServletRequest httpServletRequest = (HttpServletRequest) request;
      String token = resolveToken(httpServletRequest);
      String requestRri = httpServletRequest.getRequestURI();

      if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
         Authentication authentication = tokenProvider.getAuthentication(token);
         //将token保存到SecurityContext对象里
         SecurityContext context = SecurityContextHolder.getContext();
         context.setAuthentication(authentication);
         log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
      } else {
         log.debug("no valid JWT token found, uri: {}", requestRri);
      }
      filterChain.doFilter(request, response);


//      //获取所有路劲
//      RequestMappingHandlerMapping mapping = SpringContextHolder.getBean(RequestMappingHandlerMapping.class);
//      // 获取url与类和方法的对应信息
//      Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
//      boolean uriBoolean = CheckUriUtils.checkUri(requestRri, map);
//      //路劲错误
//      if (!uriBoolean) {
//         JSONObject jsonObject = new JSONObject();
//         response.setContentType("application/json;charset=utf-8");
//         PrintWriter writer = response.getWriter();
//         jsonObject.put("code", ResultEnum.URI_ERROR.getCode());
//         jsonObject.put("message", ResultEnum.URI_ERROR.getMessage());
//         String result = jsonObject.toString();
//         writer.write(result);
//         writer.close();
//      }else {
//         if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
//            Authentication authentication = tokenProvider.getAuthentication(token);
//            //将token保存到SecurityContext对象里
//            SecurityContext context = SecurityContextHolder.getContext();
//            context.setAuthentication(authentication);
//            log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
//         } else {
//            log.debug("no valid JWT token found, uri: {}", requestRri);
//         }
//         filterChain.doFilter(request, response);
//      }
   }

   private String resolveToken(HttpServletRequest request) {
      SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
      String bearerToken = request.getHeader(properties.getHeader());
       if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) {
         return bearerToken.substring(7);
      }
      return null;
   }
}
